﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DTO;
using DataAccess_Layer;
using Business_Layer;
using System.Collections;
public partial class MyAdmin_NCC_GiangHang : System.Web.UI.Page
{
    string tkTenDN = null;
    string tkTenNCC = null;
    long? tkGiaTu = null;
    long? tkGiaDen = null;
    LogAction log = new LogAction();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenXem)
        {
            // xử lý quyền xem
            ((CommandField)gvDSNCC_GiangHang.Columns[0]).ShowDeleteButton = false;
            CommandField dtCmdField = ((CommandField)dtChiTietGiangHang.Fields[dtChiTietGiangHang.Fields.Count - 1]);
            dtCmdField.ShowEditButton = false;
            dtCmdField.ShowInsertButton = false;
            XoaNhieuBUTTON.Visible = false;
        }
        else if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenChinhSua)
        {
            // xử lý quyền chỉnh sửa
        }

        //Tim kiem theo parameter truyen vao theo cu phap: [TenDN=...] [TenSP=...][&GiaTu=...][&GiaDen=...]
        tkTenDN = Request.Params["TenDN"];
        tkTenNCC = Request.Params["TenNCC"];
        if (Request.Params["GiaTu"] != null)
        {
            tkGiaTu = long.Parse(Request.Params["GiaTu"]);
            tkGiaTu = tkGiaTu == -1 ? null : tkGiaTu;

            tkGiaDen = long.Parse(Request.Params["GiaDen"]);
            tkGiaDen = tkGiaDen == -1 ? null : tkGiaDen;
        }

        if (!IsPostBack)
        {
            initTextBox();
        }

        List<int> checkedCheckBoxRowIndex = getCheckedCheckBoxRowIndexes(gvDSNCC_GiangHang);
        initDataSource();
        restoreCheckedCheckBox(checkedCheckBoxRowIndex);

        if ((tkGiaDen != null || tkGiaTu != null || tkTenDN != null || tkTenNCC != null) && gvDSNCC_GiangHang.Rows.Count == 0)
        {
            lblTBKhongTimThay.Visible = true;
            dtChiTietGiangHang.Visible = false;
        }

        lblThongBaoDTView.Visible = false;
        lblThongBaoGridView.Visible = false;
    }
    private void restoreCheckedCheckBox(List<int> checkedCheckBoxRowIndex)
    {
        if (checkedCheckBoxRowIndex == null)
        {
            return;
        }

        int lastCellIndex = gvDSNCC_GiangHang.Rows[0].Cells.Count - 1;
        foreach (int rowIndex in checkedCheckBoxRowIndex)
        {
            ((CheckBox)gvDSNCC_GiangHang.Rows[rowIndex].Cells[lastCellIndex].FindControl("checkXoa")).Checked = true;
        }
    }
    private List<int> getCheckedCheckBoxRowIndexes(GridView gvDSNCC_GiangHang)
    {
        if (gvDSNCC_GiangHang.Rows.Count == 0)
        {
            return null;
        }

        List<int> rowIndexes = new List<int>();
        int lastCellIndex = gvDSNCC_GiangHang.Rows[0].Cells.Count - 1;
        foreach (GridViewRow r in gvDSNCC_GiangHang.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[lastCellIndex].FindControl("checkXoa");
            if (checkXoa.Checked)
            {
                rowIndexes.Add(r.RowIndex);
            }
        }

        return rowIndexes;
    }
    private void initDataSource()
    {
        refreshGV();
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.SelectedIndex == -1 ? 0 : gvDSNCC_GiangHang.SelectedIndex;      
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }
    private void refreshGV()
    {
        gvDSNCC_GiangHang.DataSource = DataAccess_Layer.NCC_GiangHang_DAC.timKiem_NCCGH(tkTenDN, tkTenNCC, tkGiaTu, tkGiaDen);
        gvDSNCC_GiangHang.DataBind();
    }
    private void initTextBox()
    {
        txtGiaTu_NCCGH.Text = (tkGiaTu == null) ? txtGiaTu_NCCGH.Text : tkGiaTu.ToString();
        txtGiaDen_NCCGH.Text = (tkGiaDen == null) ? txtGiaDen_NCCGH.Text : tkGiaDen.ToString();
        txtTenDangNhap_NCCGH.Text = (tkTenDN == null) ? txtTenDangNhap_NCCGH.Text : tkTenDN;
        txtTenNhaCungCap_NCCGH.Text = (tkTenNCC == null) ? txtTenNhaCungCap_NCCGH.Text : tkTenNCC;
    }

    protected void gvDSNCC_GiangHang_SelectedIndexChanged(object sender, EventArgs e)
    {
        refreshDetailViewPageIndex();
    }

    protected void dtChiTietGiangHang_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        refreshGV();
        Helper.changeGVPageIndex(gvDSNCC_GiangHang, gvDSNCC_GiangHang.PageCount - 1);
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.Rows.Count - 1;

        refreshDetailViewPageIndex();
    }

    protected void dtChiTietGiangHang_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
    {
        refreshGV();
        refreshDetailViewPageIndex();
    }
    private void refreshDetailViewPageIndex()
    {
        dtChiTietGiangHang.DataBind();
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }

    protected void btnUploadForEdit_Click(object sender, EventArgs e)
    {
        FileUpload fu = (FileUpload)dtChiTietGiangHang.FindControl("fuForEdit");
        Label statusLABEL = (Label)dtChiTietGiangHang.FindControl("lblUpdloadForEdit");
        TextBox tb = (TextBox)dtChiTietGiangHang.FindControl("txtUploadForEdit");

        try
        {
            string fullName = "";
            string filename = "images/LoaiSanPham/" + fu.FileName;
            fu.SaveAs(Server.MapPath("~/") + filename);
            fullName = "~/" + filename;
            tb.Text = fullName;
            statusLABEL.Text = "File đã được upload!";
        }
        catch (Exception ex)
        {
            statusLABEL.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }

    protected void btnTimKiem_NCCGH_Click(object sender, EventArgs e)
    {
        string tenDN = txtTenDangNhap_NCCGH.Text.Length == 0 ? null : txtTenDangNhap_NCCGH.Text;
        string tenNCC = txtTenNhaCungCap_NCCGH.Text.Length == 0 ? null : txtTenNhaCungCap_NCCGH.Text;
        long? giaTu = -1;
        long? giaDen = -1;

        if (txtGiaTu_NCCGH.Text.Length != 0)
            giaTu = long.Parse(txtGiaTu_NCCGH.Text);
        else
            giaTu = -1;

        if (txtGiaDen_NCCGH.Text.Length != 0)
            giaDen = long.Parse(txtGiaDen_NCCGH.Text);
        else
            giaDen = -1;

        string url = "NCC_GiangHang_AM.aspx?GiaTu=" + giaTu + "&GiaDen=" + giaDen;

        if (tenDN != null) url += "&TenDN=" + tenDN;
        if (tenNCC != null) url += "&TenNCC=" + tenNCC;

        Response.Redirect(url);
    }

    protected void LQDSNCC_GiangHang_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        e.Result = gvDSNCC_GiangHang.DataSource;
    }

    protected void cbbLSP_DataBound(object sender, EventArgs e)
    {
        DropDownList cbbLSP = (DropDownList)dtChiTietGiangHang.FindControl("cbbLSP");
        TextBox txtMaCLSP = (TextBox)dtChiTietGiangHang.FindControl("txtTenCLSP");

        if (dtChiTietGiangHang.CurrentMode == DetailsViewMode.Edit)
        {
            cbbLSP.SelectedValue = txtMaCLSP.Text;
        }
        else if (dtChiTietGiangHang.CurrentMode == DetailsViewMode.Insert)
        {
            txtMaCLSP.Text = cbbLSP.SelectedValue;
        }
    }

    protected void cbbLSP_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList cbbLSP = (DropDownList)dtChiTietGiangHang.FindControl("cbbLSP");
        TextBox txtMaCLSP = (TextBox)dtChiTietGiangHang.FindControl("txtTenCLSP");
        txtMaCLSP.Text = cbbLSP.SelectedValue;
    }

    protected void gvDSNCC_GiangHang_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        long id = long.Parse(e.Keys[0].ToString());
        try
        {
            DataAccess_Layer.NCC_GiangHang_DAC.delete(id);
        }
        catch (System.Exception ex)
        {
            Response.Write(Helper.CreateMessageBox("Không thể xóa Record có ID " + id));
            return;
        }

        Response.Write(Helper.CreateMessageBox("Đã xóa Record có ID = " + id));
        initDataSource();
    }

    protected void gvDSNCC_GiangHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        Helper.changeGVPageIndex(gvDSNCC_GiangHang, e.NewPageIndex);
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.Rows.Count > 0 ? 0 : -1;
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }

    protected void XoaNhieuBUTTON_Click(object sender, EventArgs e)
    {
        string ids = "";
        List<long> deletedIDs = new List<long>();
        int lastCellIndex = gvDSNCC_GiangHang.Rows[0].Cells.Count - 1;
        foreach (GridViewRow r in gvDSNCC_GiangHang.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[lastCellIndex].FindControl("checkXoa");
            if (checkXoa.Checked)
            {
                long id = long.Parse(r.Cells[1].Text);
                deletedIDs.Add(id);
                ids += id.ToString() + ", ";
            }
        }

        lblThongBaoGridView.Visible = true;
        lblThongBaoGridView.Text = "Xóa thành công record: " + ids.Substring(0, ids.LastIndexOf(", "));
        //log
        log.TenLoaiCapNhat = "Xóa";
        log.Ngay = DateTime.Now;
        log.TenBang = "Bảng Nhà cung cấp giang hàng";
        log.TenLoaiDangNhap = "Admin";
        log.TenDangNhap = Helper.getCurrentAdminUserName(Session);
        string logText = "";
        log.DuLieuCu = "record ID:" + ids.Substring(0, ids.LastIndexOf(", "));
        logText = "X";
        log.DuLieuMoi = logText;
        Log_BUS.insert(log);
        //log
        try
        {
            DataAccess_Layer.NCC_GiangHang_DAC.delete(deletedIDs);
        }
        catch (System.Exception ex)
        {
            lblThongBaoGridView.Text = "Xóa thất bại!";
        }
     
        initDataSource();
        refreshDetailViewPageIndex();
    }
    protected void LQDSNCC_GiangHang_Updating(object sender, LinqDataSourceUpdateEventArgs e)
    {
        //log
        try
        {
            log.TenLoaiCapNhat = "cập nhật";
            log.Ngay = DateTime.Now;
            log.TenBang = "Bảng nhà cung cấp giang hàng";
            log.TenLoaiDangNhap = "Adminstator";
            log.TenDangNhap = Helper.getCurrentAdminUserName(Session);

            DataAccess_Layer.NCC_GiangHang logO = (DataAccess_Layer.NCC_GiangHang)e.OriginalObject;

            log.DuLieuCu = "Tên đăng nhập NCC: " + logO.NCC_UN
                + "..\nTên sản phẩm: " + logO.Hinh
                + "..\nChủng loại sản phẩm: " + logO.MaChungLoaiSP
                + "..\nmô tả: " + logO.MoTa
                + "..\nHình: " + logO.Hinh
                + "..\ngiá: " + logO.Gia
                + "..\nsố lượng tối thiểu: " + logO.SLToiThieu
                + "..\nNgày cập nhật: " + logO.NgayCapNhatSaucung;




            logO = (DataAccess_Layer.NCC_GiangHang)e.NewObject;
            log.DuLieuMoi = "Tên đăng nhập NCC: " + logO.NCC_UN
                + "..\nTên sản phẩm: " + logO.Hinh
                + "..\nChủng loại sản phẩm: " + logO.MaChungLoaiSP
                + "..\nmô tả: " + logO.MoTa
                + "..\nHình: " + logO.Hinh
                + "..\ngiá: " + logO.Gia
                + "..\nsố lượng tối thiểu: " + logO.SLToiThieu
                + "..\nNgày cập nhật: " + logO.NgayCapNhatSaucung;
            Log_BUS.insert(log);
        }
        catch { }
        //log
        DataAccess_Layer.NCC_GiangHang newOrder = (DataAccess_Layer.NCC_GiangHang)e.NewObject;

        lblThongBaoDTView.Visible = true;
        try
        {
            DataAccess_Layer.NCC_GiangHang_DAC.update(newOrder);
            lblThongBaoDTView.Text = "Cập nhật thành công record có ID là " + newOrder.ID;
        }
        catch (System.Exception ex)
        {
            lblThongBaoDTView.Text = "Cập nhật thất bại record có ID là " + newOrder.ID;
        }

        e.Cancel = true;
    }
    protected void LQDSHoaDon_AM_Inserted(object sender, LinqDataSourceStatusEventArgs e)
    {
        //log
        try
        {
            log.TenLoaiCapNhat = "Thêm";
            log.Ngay = DateTime.Now;
            log.TenBang = "Bảng Nhà cung cấp giang hàng";
            log.TenLoaiDangNhap = "Adminstator";
            log.TenDangNhap = Helper.getCurrentAdminUserName(Session);

            DataAccess_Layer.NCC_GiangHang logO;

            log.DuLieuCu = "X";

            logO = (DataAccess_Layer.NCC_GiangHang)e.Result;
            log.DuLieuMoi = "Tên đăng nhập NCC: " + logO.NCC_UN
                + "..\nTên sản phẩm: " + logO.Hinh
                + "..\nChủng loại sản phẩm: " + logO.MaChungLoaiSP
                + "..\nmô tả: " + logO.MoTa
                + "..\nHình: " + logO.Hinh
                + "..\ngiá: " + logO.Gia
                + "..\nsố lượng tối thiểu: " + logO.SLToiThieu
                + "..\nNgày cập nhật: " + logO.NgayCapNhatSaucung;
            Log_BUS.insert(log);
        }
        catch { }
        //log
        lblThongBaoDTView.Visible = true;
        DataAccess_Layer.NCC_GiangHang newOrder = (DataAccess_Layer.NCC_GiangHang)e.Result;

        if (e.Exception == null)
        {
            lblThongBaoDTView.Text = "Thêm thành công record có ID là " + newOrder.ID;
            return;
        }

        lblThongBaoDTView.Text = "Thêm thất bại record!";
        e.ExceptionHandled = true;
    }
}